package com.navi.util;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by admin on 2017/6/21.
 */
public class HistoryContext {
    private static String hostName;
    private static String ip;

    private static ThreadLocal<String> serviceName = new ThreadLocal<String>();
    private static ThreadLocal<String> serviceEventNumber = new ThreadLocal<String>();
    private static ThreadLocal<List<String>> jsonEntityList = new ThreadLocal<List<String>>();


    static {
        try {
            InetAddress inetAddr = InetAddress.getLocalHost();
            byte[] addr = inetAddr.getAddress();
            // Convert to dot representation
            String ipAddr = "";
            for (int i = 0; i < addr.length; i++) {
                if (i > 0) {
                    ipAddr += ".";
                }
                ipAddr += addr[i] & 0xFF;
            }
            String hostname = inetAddr.getHostName();
            if (hostname.length() > 20) {
                setHostName(hostname.substring(0, 20));
            } else {
                setHostName(hostname);
            }
            setIp(ipAddr);

//            System.setProperty("hostname", hostname);
//            System.setProperty("ip", ipAddr);
        } catch (UnknownHostException e) {
            System.out.println("Host not found: " + e.getMessage());
        }
    }

    public static void addJsonEntity(String json) {
        List<String> jsonList = getJsonEntityList();
        if (jsonList == null) {
            jsonList = new ArrayList<String>();
        }
        jsonList.add(json);
        setJsonEntityList(jsonList);
    }

    public static void clear(Class clazz) {
        jsonEntityList.set(null);
        serviceName.set(clazz.getSimpleName());
        serviceEventNumber.set(UUID.randomUUID().toString());
    }

    public static List<String> getJsonEntityList() {
        return jsonEntityList.get();
    }

    public static void setJsonEntityList(List<String> value) {
        jsonEntityList.set(value);
    }

    public static String getServiceName() {
        return serviceName.get();
    }

    public static void setServiceName(String value) {
        serviceName.set(value);
    }

    public static String getServiceEventNumber() {
        return serviceEventNumber.get();
    }

    public static void setServiceEventNumber(String value) {
        serviceEventNumber.set(value);
    }

    public static String getHostName() {
        return hostName;
    }

    public static void setHostName(String hostName) {
        HistoryContext.hostName = hostName;
    }

    public static String getIp() {
        return ip;
    }

    public static void setIp(String ip) {
        HistoryContext.ip = ip;
    }

}
